package com.weblog.weblogapi.controller;

import com.weblog.weblogapi.utils.QiniuUtils;
import com.weblog.weblogapi.vo.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("upload")
public class UploadController {
    @Autowired
    private QiniuUtils qiniuUtils;
    //上传用户头像
    @PostMapping("user")
    public Result uploadUser(@RequestParam("image")MultipartFile file){
        String originalFileName = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString()+"."+ StringUtils.substringAfterLast(originalFileName,".");
        boolean upload=qiniuUtils.upload(file,fileName,"user");
        if(upload){
            return Result.success(QiniuUtils.url+"user/"+fileName);
        }
        return Result.fail(20001,"上传失败");
    }
    //上传文章图片
    @PostMapping("weblog")
    public Result uploadWeBlog(@RequestParam("image")MultipartFile file){
        String originalFileName = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString()+"."+ StringUtils.substringAfterLast(originalFileName,".");
        boolean upload=qiniuUtils.upload(file,fileName,"weblog");
        if(upload){
            return Result.success(QiniuUtils.url+"weblog/"+fileName);
        }
        return Result.fail(20001,"上传失败");
    }
}
